using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace AnimTool
{
    public partial class PreviewForm : Form
    {
        private bool playing = false;
        Thread t;
        public PreviewForm()
        {
            InitializeComponent();

            t = new Thread(new ThreadStart(InvalidateThis));
            t.Start();
        }
        DateTime last, current;
        int currentDelay;
        public void Play()
        {
            Size = new Size(96,96);
            playing = true;
            currentFrameIndex = 0;
            currentFrame = animation.Frames[currentFrameIndex];
        }

        public void Kill()
        {
            t.Abort();
        }
        public void InvalidateThis()
        {
            while (true)
            {
                while (playing)
                {
                    Thread.Sleep(1);
                    Invalidate();
                }
                Thread.Sleep(100);
            }
        }
        public void Stop()
        {
            playing = false;
        }

        Form1.Animation animation;
        public Form1.Animation Animation
        {
            get { return animation; }
            set 
            {
                animation = value;
                //Size = new Size(animation.Frames[0].width + 2, animation.Frames[0].height + 2);

            }
        }
        Form1.Frame currentFrame;
        int currentFrameIndex;

        int scale = 3;
        private void PreviewForm_Paint(object sender, PaintEventArgs e)
        {                        
            last = current;
            current = DateTime.Now;
            TimeSpan ts = (current - last);
            currentDelay += ts.Milliseconds;

            if (currentDelay >= currentFrame.delay)
            {                
                currentFrameIndex ++;
                if (currentFrameIndex >= animation.Frames.Count) currentFrameIndex = 0;
                currentFrame = animation.Frames[currentFrameIndex];
                currentDelay = 0;
            }

            Image i = Form1.ImageMap[currentFrame.resource];

            Graphics g = e.Graphics;
            Rectangle src = new Rectangle(currentFrame.x, currentFrame.y, currentFrame.width, currentFrame.height);
            Rectangle dst = new Rectangle(1, 1, currentFrame.width*scale, currentFrame.height*scale);
            g.DrawImage(i, dst, src, GraphicsUnit.Pixel);
            g.DrawRectangle(new Pen(Brushes.Black, 1), new Rectangle(0, 0, currentFrame.width * scale + 1, currentFrame.height * scale + 1));
        }
    }
}